import {DatePipe} from '@angular/common';
import {Component, OnInit} from '@angular/core';
import {CommonTool} from '../../common/common.tool';
import {BasicService} from '../basic.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {environment} from '../../../environments/environment';
import {DictService} from '../../common/service/dict.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [DatePipe]
})
export class LoginComponent implements OnInit {
  constructor(public basicService: BasicService,
              private dictService: DictService,
              private message: NzMessageService,
              public modalService: NzModalService,
              private router: Router) {
  }

  ngOnInit(): void {
    const param = CommonTool.getUrlParam(location.href);
    let code = null;
    let accessToken = null;
    if (param['code']) {
      const state = localStorage.getItem('state');
      if (param['state'] === state) {
        code = param['code'];
      } else {
        this.message.error('state错误！');
        this.basicService.jumpLogin();
      }
    } else if (param['accessToken']) {
      accessToken = param['accessToken'];
    } else {
      this.basicService.jumpLogin();
    }
    if (code != null || accessToken != null) {
      this.basicService.getToken(code, accessToken).subscribe(res => {
        let authorityCodes = res['authorityCodes'];
        authorityCodes = authorityCodes.concat(res['groupAuthorityCodes']);
        if (!authorityCodes || authorityCodes.length === 0) {
          this.modalService.info({
            nzTitle: '你没有访问该系统的权限！',
            nzContent: '<p>已向管理员申请，请保存账号联系该系统管理员！</p><p>用户账号：<b>' + res['account'] + '</b></p>',
            nzOkText: '确认',
            nzOnOk: () => {
              this.basicService.jumpLogin();
            }
          });
        } else {
          this.basicService.initLogin(res, authorityCodes, () => {
            localStorage.removeItem('state');
            this.router.navigate(['/home']);
          });
        }
      }, error => {
        this.basicService.jumpLogin();
      });
    }
  }
}
